package dynamic.mybatisplus.core.toolkit;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import dynamic.metadata.EntityClass;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

public class DMPJTableMapperHelper {

    private static final Map<EntityClass , Class<?>> CACHE = new ConcurrentHashMap<>();
    private static final Map<Class<?>,EntityClass> CACHE_REVERSE = new ConcurrentHashMap<>();
    private static final Map<String, Class<?>> CACHE_MAPPER = new ConcurrentHashMap<>();


    public static void init(EntityClass clazz, Class<?> mapper) {
        if (clazz != null && mapper != null) {
            CACHE.put(clazz, mapper);
            CACHE_REVERSE.put(mapper, clazz);
            CACHE_MAPPER.put(mapper.getName(), mapper);
        }
    }

    public static Class<?> getMapper(EntityClass clazz) {
        return Optional.ofNullable(clazz).map(m -> CACHE.get(clazz)).orElse(null);
    }

    public static EntityClass getEntity(Class<?> clazz) {
        return Optional.ofNullable(clazz).map(m -> CACHE_REVERSE.get(clazz)).orElse(null);
    }

    public static Class<?> getMapperForName(String name) {
        if (StringUtils.isBlank(name)) {
            return null;
        }
        return CACHE_MAPPER.get(name);
    }
}
